package dao;

import entity.PaymentRecord;
import util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PaymentRecordDao {
    public List<PaymentRecord> getPaymentRecordsByOwnerId(Integer ownerId) {
        String sql = "SELECT pr.*, ft.name as fee_type_name FROM payment_record pr " +
                "JOIN fee_type ft ON pr.fee_type_id = ft.id " +
                "WHERE pr.owner_id = ? ORDER BY pr.payment_time DESC";

        List<PaymentRecord> records = new ArrayList<>();

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, ownerId);

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    PaymentRecord record = new PaymentRecord();
                    record.setId(rs.getInt("id"));
                    record.setOwnerId(rs.getInt("owner_id"));
                    record.setFeeTypeId(rs.getInt("fee_type_id"));
                    record.setAmount(rs.getBigDecimal("amount"));
                    record.setQuantity(rs.getBigDecimal("quantity"));
                    record.setPaymentTime(rs.getTimestamp("payment_time"));
                    record.setFeeTypeName(rs.getString("fee_type_name"));
                    records.add(record);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("获取缴费记录失败", e);
        }
        return records;
    }

    public void addPaymentRecord(PaymentRecord record, Connection conn) throws SQLException {
        String sql = "INSERT INTO payment_record (owner_id, fee_type_id, amount, quantity, payment_time) " +
                "VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, record.getOwnerId());
            stmt.setInt(2, record.getFeeTypeId());
            stmt.setBigDecimal(3, record.getAmount());
            stmt.setBigDecimal(4, record.getQuantity());
            stmt.executeUpdate();
        }
    }

    @Deprecated
    public void addPaymentRecord(PaymentRecord record) {
        try (Connection conn = DBUtil.getConnection()) {
            addPaymentRecord(record, conn);
        } catch (Exception e) {
            throw new RuntimeException("添加支付记录失败", e);
        }
    }
}